const express = require('express');
const router = express.Router();
const db = require('../db'); // 假设db.js是数据库连接模块

// 搜索动物
router.get('/', async (req, res) => {
  try {
    let query = 'SELECT * FROM animals WHERE 1=1'; // 基础查询语句
    const queryParams = [];

    // 根据请求参数动态构建查询条件
    if (req.query.species) {
      query += ' AND species = ?';
      queryParams.push(req.query.species);
    }
    if (req.query.ageMin && req.query.ageMax) {
      query += ' AND age BETWEEN ? AND ?';
      queryParams.push(req.query.ageMin, req.query.ageMax);
    }
    if (req.query.gender) {
      query += ' AND gender = ?';
      queryParams.push(req.query.gender);
    }

    const [rows] = await db.query(query, queryParams);
    res.status(200).json(rows);
  } catch (error) {
    console.error(error);
    res.status(500).send('Error searching for animals.');
  }
});

module.exports = router;